package com.zlm.spider.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Harbour
 * @date 2021-04-13 8:19
 */
public class JDBCUtils {

    private static volatile DruidDataSource dataSource = null;
    private static final Properties prop = PropertiesUtils.getProperties("application.properties");

    public static Connection getConnection () {
        if (dataSource == null) {
            synchronized (JDBCUtils.class) {
                if (dataSource == null) {
                    dataSource = new DruidDataSource();
                    dataSource.setUrl(prop.getProperty("spring.datasource.url"));
                    dataSource.setDriverClassName("spring.datasource.driverClassName"); //这个可以缺省的，会根据url自动识别
                    dataSource.setUsername("spring.datasource.username");
                    dataSource.setPassword("spring.datasource.password");
                    //下面都是可选的配置
                    dataSource.setInitialSize(10);  //初始连接数，默认0
                    dataSource.setMaxActive(30);  //最大连接数，默认8
                    dataSource.setMinIdle(10);  //最小闲置数
                    dataSource.setMaxWait(2000);  //获取连接的最大等待时间，单位毫秒
                    dataSource.setPoolPreparedStatements(true); //缓存PreparedStatement，默认false
                    dataSource.setMaxOpenPreparedStatements(20); //缓存PreparedStatement的最大数量，默认-1（不缓存）。
                }
            }
        }
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
